﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QWeiboSDK;
using System.Configuration;
using System.Web;
using System.Net;
using Windvoice.Library;
using System.Xml;

namespace Windvoice.Authorize
{
    public class QQConnector : IOAuthConnector
    {
        private static string AppKey = ConfigurationManager.AppSettings["qq_key"];
        private static string AppSecret = ConfigurationManager.AppSettings["qq_secret"];

        public string GetRequestToken(string callbackUrl)
        {
            string url = "http://open.t.qq.com/cgi-bin/request_token";
            List<Parameter> parameters = new List<Parameter>();
            OauthKey oauthKey = new OauthKey();
            oauthKey.customKey = AppKey;
            oauthKey.customSecret = AppSecret;
            oauthKey.callbackUrl = callbackUrl;

            QWeiboRequest request = new QWeiboRequest();
            string[] result = ParseToken(request.SyncRequest(url, "GET", oauthKey, parameters, null));
            if (result == null || result.Length != 2)
                throw new Exception("QQ 死活连不上啊");

            HttpContext.Current.Session["oauth_token"] = result[0];
            HttpContext.Current.Session["oauth_token_secret"] = result[1];

            string redirect = String.Format("http://open.t.qq.com/cgi-bin/authorize?oauth_token={0}", result[0]);

            return redirect;
        }

        public void GetAccessToken()
        {
            if (HttpContext.Current.Request["oauth_verifier"] != null)
            {
                string url = "http://open.t.qq.com/cgi-bin/access_token";
                List<Parameter> parameters = new List<Parameter>();
                OauthKey oauthKey = new OauthKey();
                oauthKey.customKey = AppKey;
                oauthKey.customSecret = AppSecret;
                oauthKey.tokenKey = HttpContext.Current.Session["oauth_token"].ToString();
                oauthKey.tokenSecret = HttpContext.Current.Session["oauth_token_secret"].ToString();
                oauthKey.verify = HttpContext.Current.Request["oauth_verifier"];

                QWeiboRequest request = new QWeiboRequest();
                string[] result = ParseToken(request.SyncRequest(url, "GET", oauthKey, parameters, null));
                if (result == null || result.Length != 2)
                    throw new Exception("QQ 死活连不上啊");

                HttpContext.Current.Session["oauth_token"] = result[0];
                HttpContext.Current.Session["oauth_token_secret"] = result[1];
            }
            else
            {
                throw new Exception("啊哦，看来腾讯抽风了，连不上啊！");
            }
        }

        public User GetUser()
        {
            OauthKey oauthKey = new OauthKey();
            oauthKey.customKey = AppKey;
            oauthKey.customSecret = AppSecret;
            oauthKey.tokenKey = HttpContext.Current.Session["oauth_token"].ToString();
            oauthKey.tokenSecret = HttpContext.Current.Session["oauth_token_secret"].ToString();
            oauthKey.verify = HttpContext.Current.Request["oauth_verifier"];

            user u = new user(oauthKey,"xml");

            return this.ResolveUser(u.info());
        }

        private User ResolveUser(string xml)
        {
            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(xml);

            User user = new User();

            user.DisplayName = xdoc.SelectSingleNode("/root/data/nick").InnerText;
            user.Gender = xdoc.SelectSingleNode("/root/data/sex").InnerText == "1" ? 1 : 0;
            user.Location = xdoc.SelectSingleNode("/root/data/location").InnerText;
            user.PortraitUrl = xdoc.SelectSingleNode("/root/data/head").InnerText + "/40";
            user.Url = String.Empty;
            user.Domain = xdoc.SelectSingleNode("/root/data/homepage ").InnerText;
            user.Description = xdoc.SelectSingleNode("/root/data/introduction ").InnerText;
            user.Verified = true;
            user.UniqueID = xdoc.SelectSingleNode("/root/data/openid ").InnerText;
            user.Source = (int)UserSource.QQ;

            return user;
        }

        private string[] ParseToken(string response)
        {
            if (string.IsNullOrEmpty(response))
            {
                return null;
            }

            string[] tokenArray = response.Split('&');

            if (tokenArray.Length < 2)
            {
                return null;
            }

            string strTokenKey = tokenArray[0];
            string strTokenSecrect = tokenArray[1];

            string[] token1 = strTokenKey.Split('=');
            if (token1.Length < 2)
            {
                return null;
            }
            string tokenKey = token1[1];

            string[] token2 = strTokenSecrect.Split('=');
            if (token2.Length < 2)
            {
                return null;
            }
            string tokenSecret = token2[1];

            return new string[] { tokenKey, tokenSecret };
        }
    }
}
